﻿using Sc.Cache;
using Sc.Domain;
using Sc.Persistence;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sc.Service
{
    public class Car_InsuranceService
    {
        /// <summary>
        /// 保险数据持久层
        /// </summary>
        private readonly Car_InsuranceDAO dao = new Car_InsuranceDAO();
        /// <summary>
        /// 待办事宜服务层
        /// </summary>
        private Sys_ToDoListService service = new Sys_ToDoListService();
        /// <summary>
        /// 意见数据持久层
        /// </summary>
        private OpinionsDAL oDao = new OpinionsDAL();
        /// <summary>
        /// 保存车辆保险数据
        /// </summary>
        /// <param name="ent">页面数据</param>
        /// <param name="list">附件列表</param>
        /// <returns></returns>
        public ReturnModel SaveData(Car_Insurance ent, IList<Sys_Attachments> list)
        {
            if (list != null && list.Count > 0)
            {
                ent.HasAttachments = true;
            }
            //Sys.SysWebservice opa = CommService.IntanceSys();
            //var wf = opa.GetWF("WF008", ent.OrgzNo);
            ent.ApproalUsers = "temp"; // wf.AppoalUsers;
            ent.NodeCount = 0;
            try
            {
                var bussId = dao.Add(ent);
                //IList<Sys_ToDoList> tList = new List<Sys_ToDoList>();
                //var firstUs = wf.FirstNodeUsers.Split(',');
                //var car = ProjectCache.CarInfo[ent.CarId];
                //for (int i = 0; i < firstUs.Length; i++)
                //{
                //    Sys_ToDoList todo = new Sys_ToDoList();
                //    RefDataRecord rc = new RefDataRecord(firstUs[i]);
                //    todo.UserId = rc.ObjectId;
                //    todo.ActionURL = ent.ToDoUrl;
                //    todo.CreaterName = "系统";
                //    todo.Source = "CISE" + bussId;
                //    todo.UrgencyDegree = 0;
                //    todo.Name = car.CarNo + "保险购买申请流程";
                //    tList.Add(todo);
                //}
                //service.SaveToDoList(tList);
                if (list != null)
                {
                    new Sys_AttachmentsDAO().SaveAttachments(list, bussId);
                }
                ReturnModel succ = new ReturnModel() { SourceId = bussId, Message = "操作成功" };
                return succ;
            }
            catch (Exception ex)
            {
                ReturnModel err = new ReturnModel() { SourceId = 0, Message = ex.Message };
                return err;
            }
        }
        /// <summary>
        /// 获取保险列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <returns></returns>
        public CommModel<Car_Insurance> GetList(int userId, int pageSize, int pageIndex)
        {
            Hashtable param = new Hashtable();
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", "AND UserId=" + userId);
            param.Add("A4", "Car_Insurance");
            param.Add("A5", "BeginTime DESC");
            var ht = CommDAO.CommPagination(param);
            if (Convert.ToInt32(ht["record"]) > 0)
            {
                DataTable dt = ht["data"] as DataTable;
                List<Car_Insurance> list = new List<Car_Insurance>();
                foreach (DataRow item in dt.Rows)
                {
                    list.Add(DataRowToModel(item));
                }
                CommModel<Car_Insurance> ent = new CommModel<Car_Insurance>();
                ent.Data = list;
                ent.PageCount = Convert.ToInt32(ht["PageCount"]);
                ent.RecordCount = Convert.ToInt32(ht["record"]);
                return ent;
            }
            return null;
        }

        /// <summary>
        /// 获取车辆保险
        /// </summary>
        /// <param name="orgz">机构ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <param name="start">用车开始时间</param>
        /// <param name="end">用车结束时间</param>
        /// <returns></returns>
        public CommModel<Car_Insurance> GetList(int orgz, int pageSize, int pageIndex, string start, string end)
        {
            string where = string.Empty;
            if (orgz > 0)
            {
                where = "AND OrgzNo=" + orgz;
            }
            if (!string.IsNullOrEmpty(start))
            {
                where += " AND BeginTime>='" + start + "' AND BeginTime<='" + end + "'";
            }
            Hashtable param = new Hashtable();
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", where);
            param.Add("A4", "VW_Car_Insurance");
            param.Add("A5", "BeginTime DESC");
            var ht = CommDAO.CommPagination(param);
            DataTable dt = ht["data"] as DataTable;
            List<Car_Insurance> list = new List<Car_Insurance>();
            foreach (DataRow item in dt.Rows)
            {
                list.Add(DataRowToModel(item));
            }
            CommModel<Car_Insurance> ent = new CommModel<Car_Insurance>();
            ent.Data = list;
            ent.PageCount = Convert.ToInt32(ht["PageCount"]);
            ent.RecordCount = Convert.ToInt32(ht["record"]);
            return ent;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Car_Insurance DataRowToModel(DataRow row)
        {
            Car_Insurance model = new Car_Insurance();
            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = int.Parse(row["Id"].ToString());
                }
                if (row["CarId"] != null && row["CarId"].ToString() != "")
                {
                    model.CarId = int.Parse(row["CarId"].ToString());
                }
                if (row["TypeId"] != null && row["TypeId"].ToString() != "")
                {
                    model.TypeId = int.Parse(row["TypeId"].ToString());
                }
                if (row["InsuranceNo"] != null)
                {
                    model.InsuranceNo = row["InsuranceNo"].ToString();
                }
                if (row["InsuranceMoney"] != null && row["InsuranceMoney"].ToString() != "")
                {
                    model.InsuranceMoney = decimal.Parse(row["InsuranceMoney"].ToString());
                }
                if (row["InsuranceCompany"] != null)
                {
                    model.InsuranceCompany = row["InsuranceCompany"].ToString();
                }
                if (row["BeginTime"] != null && row["BeginTime"].ToString() != "")
                {
                    model.BeginTime = DateTime.Parse(row["BeginTime"].ToString());
                }
                if (row["EndTime"] != null && row["EndTime"].ToString() != "")
                {
                    model.EndTime = DateTime.Parse(row["EndTime"].ToString());
                }
                if (row["HasAttachments"] != null && row["HasAttachments"].ToString() != "")
                {
                    if ((row["HasAttachments"].ToString() == "1") || (row["HasAttachments"].ToString().ToLower() == "true"))
                    {
                        model.HasAttachments = true;
                    }
                    else
                    {
                        model.HasAttachments = false;
                    }
                }
                if (row["State"] != null && row["State"].ToString() != "")
                {
                    model.State = int.Parse(row["State"].ToString());
                }
                if (row["InstanceState"] != null && row["InstanceState"].ToString() != "")
                {
                    model.InstanceState = int.Parse(row["InstanceState"].ToString());
                }
                if (row["TypeName"] != null)
                {
                    model.ApproalUsers = row["TypeName"].ToString();
                }
                if (row["NodeCount"] != null && row["NodeCount"].ToString() != "")
                {
                    model.NodeCount = int.Parse(row["NodeCount"].ToString());
                }
                if (row["UserId"] != null && row["UserId"].ToString() != "")
                {
                    model.UserId = int.Parse(row["UserId"].ToString());
                }
            }
            return model;
        }
        /// <summary>
        /// 获取单个保险数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <summary>
        public Car_Insurance GetDetail(int id)
        {
            var tmp = this.dao.GetDetail(id);
            tmp.CarNo = ProjectCache.CarInfo[tmp.CarId].CarNo;
            tmp.UserName = CommService.IntanceSys().GetUserById(tmp.UserId).Name;
            //if (tmp != null && tmp.HasAttachments)
            //    tmp.AttactList = new Sys_AttachmentsDAO().GetList("CISE", id);
            //tmp.OpinionList = new OpinionsBLL().GetList("CISE" + id);
            tmp.OpinionList = new List<Opinions>();
            return tmp;
        }

        #region  BasicMethod
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Car_Insurance model)
        {
            return dao.Add(model) > 0;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Car_Insurance model)
        {
            return dao.Update(model) > 0;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {

            return dao.Delete(Id);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool DeleteList(string idlist)
        {
            return dao.DeleteList(idlist);
        }
        #endregion
        /// <summary>
        /// 审批保险购买申请
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <param name="userId">当前用户Id</param>
        /// <param name="opa">操作</param>
        /// <param name="todoId">待办事宜ID</param>
        /// <param name="opContext">审批意见</param>
        /// <returns></returns>
        public ReturnModel Approal(int bid, int userId, int opa, int todoId, string opContext)
        {
            var ent = this.GetDetail(bid);
            if (ent == null) return new ReturnModel() { SourceId = 0, Message = "请上传正确的业务ID" };
            var upUsers = CommService.UpdateApproalUers(ent.ApproalUsers, userId, ent.NodeCount);
            var upNodeCount = CommService.IsUpdateNodeCount(ent.ApproalUsers, userId, ent.NodeCount);
            var list = new List<Sys_ToDoList>();
            if (opa == 1)//拒绝
            {
                ent.InstanceState = 2;
                Sys_ToDoList todo = new Sys_ToDoList();
                todo.ActionURL = string.Empty;
                todo.CreaterName = "系统";
                todo.Name = "您的保险购买申请已被拒绝";
                todo.Source = "CISE" + ent.Id;
                todo.State = 0;
                todo.UrgencyDegree = 0;
                todo.UserId = ent.UserId;
                list.Add(todo);
            }
            else
            {
                if (ent.NodeCount == 1)
                {
                    ent.InstanceState = 3;
                    Sys_ToDoList todo = new Sys_ToDoList();
                    todo.ActionURL = string.Empty;
                    todo.CreaterName = "系统";
                    todo.Name = "您的保险购买申请已通过";
                    todo.Source = "CISE" + ent.Id;
                    todo.State = 0;
                    todo.UrgencyDegree = 0;
                    todo.UserId = ent.UserId;
                    list.Add(todo);
                }
                else
                {
                    ent.InstanceState = 1;
                    if (upNodeCount < ent.NodeCount)
                    {
                        var nextUsers = CommService.FindNextUsers(ent.ApproalUsers, userId, ent.NodeCount);
                        var to = service.GetDetail(todoId);
                        for (int i = 0; i < nextUsers.Count; i++)
                        {
                            Sys_ToDoList todo = new Sys_ToDoList();
                            todo.ActionURL = to.ActionURL;
                            todo.CreaterName = "系统";
                            todo.Name = to.Name;
                            todo.Source = to.Source;
                            todo.State = 0;
                            todo.UrgencyDegree = 0;
                            todo.UserId = nextUsers[i];
                            list.Add(todo);
                        }
                    }
                }
            }
            try
            {
                ent.ApproalUsers = upUsers;
                ent.NodeCount = upNodeCount;
                var rs = ent.InstanceState == 2 ? service.UpdateAll("CISE" + bid, 1) : service.Update(new Sys_ToDoList() { Id = todoId, State = 1 });
                if (list != null)
                    service.SaveToDoList(list);
                Opinions op = new Opinions()
                {
                    Context = opContext,
                    CreateTime = DateTime.Now,
                    Source = "CISE" + ent.Id,
                    UserId = userId
                };
                oDao.Add(op);
                var bussId = this.dao.Update(ent);
                ReturnModel succ = new ReturnModel() { SourceId = bussId, Message = "操作成功" };
                return succ;
            }
            catch (Exception ex)
            {
                ReturnModel err = new ReturnModel() { SourceId = 0, Message = ex.Message };
                return err;
            }
        }
    }
}